package cn.yunhe.service;

import cn.yunhe.dao.UserDao;
import cn.yunhe.entity.Page;
import cn.yunhe.entity.User;
import cn.yunhe.util.PageUtil;
import cn.yunhe.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserService {

        SqlSession session = null;
        UserDao userDao = null;
        public void init(){
            session = SqlSessionFactoryUtil.getSession();
            userDao = session.getMapper(UserDao.class);
        }


    private  void destory(){
        session.close();
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    public Boolean register(User user) {
        init();
        boolean flag = userDao.register(user);
        session.commit();
        destory();
        return flag;
    }

    /**
     * 登录
     *
     * @param user
     * @return
     */
    public User login(User user) {
        init();
        User u = null;
        u = userDao.login(user);
        destory();
        return u;

    }
    /**
     * 用户分页
     */
    public List<User> getUserByPage(int currPage, String keyword) {
        init();
        Page page = new Page();
        page.setPageStart(PageUtil.PAGE_SIZE * (currPage - 1));   //pageSize*(currPage-1)
        page.setPageSize(PageUtil.PAGE_SIZE);
        page.setKeyword(keyword);

        List<User> userList = userDao.getAllUserByPage(page);
        destory();
        return userList;
    }

    /**
     * 用户总条数
     * @return
     */
    public int getUserCount() {
        init();
        return  userDao.getUserCount();
    }

    /**
     * 修改用户
     * @param user
     * @return
     */

    public  boolean updateUser(User user){
        init();
        boolean flag = userDao.updateUser(user);
        session.commit();
        destory();
        return flag;

    }

    /**
     * 根据ID查某个用户
     * @param uid
     * @return
     */

     public User getUserById(int uid){

         init();
         return userDao.getUserById(uid);
     }




     public  boolean deleteUser(int  uid){
         init();
         boolean flag = userDao.deleteUser(uid);
         session.commit();
         destory();
         return flag;
     }
     public User selectIdbyName(User user){
         init();
        User user1 =  userDao.selectIdByName(user);
        return  user1;
    }

    /**
     * 后台用户添加
     * @param user
     * @return
     */
      public  boolean addAdminUser(User user){
          init();
          boolean flag = userDao.addAdminUser(user);
          session.commit();
          destory();
          return flag;

      }


}
